package com.eascs.finance.admin.web.controller;

import java.io.IOException;
import java.net.URLEncoder;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.ftp.FtpConfig;
import com.eascs.common.ftp.FtpHelper;
import com.eascs.common.util.UrlUtil;
import com.eascs.finance.admin.common.controller.BaseMasterViewController;
import com.eascs.finance.admin.common.entity.Attachment;
import com.eascs.finance.admin.web.service.AttachmentService;
import com.eascs.web.exception.RedirectException;

@Controller
public class AttachmentViewController extends BaseMasterViewController {
	@Inject
	private AttachmentService attachmentService;

	@Inject
	private FtpConfig ftpConfig;

	@RequestMapping("/attachment/view")
	public void viewAttachment(String id, HttpServletResponse httpServletResponse) {
		Attachment attachment = attachmentService.getAttachmentById(id);
		try {
			if ("pdf".equals(attachment.getSuffix())) {
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(attachment.getName(), "utf-8"));
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			} else if ("gif".equals(attachment.getSuffix()) || "png".equals(attachment.getSuffix()) || "bmp".equals(attachment.getSuffix()) || "jpg".equals(attachment.getSuffix())) {
				httpServletResponse.setContentType("image/" + attachment.getSuffix());
			} else {
				String url = "/attachment/download/" + URLEncoder.encode(attachment.getName(), "utf-8");
				url = UrlUtil.appendUrl(url, "id", id);
				throw new RedirectException(url);
			}
			FtpHelper.download(ftpConfig, httpServletResponse.getOutputStream(), attachment.getFilePath());
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
		}
		return;
	}

	@RequestMapping("/attachment/download/*")
	public void downloadAttachment(String id, HttpServletResponse httpServletResponse) {
		Attachment attachment = attachmentService.getAttachmentById(id);
		try {
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(attachment.getName(), "utf-8"));
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			FtpHelper.download(ftpConfig, httpServletResponse.getOutputStream(), attachment.getFilePath());
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
		}
		return;
	}

}
